/**
 * 文件管理器
 * */

import React, {Component} from 'react';
import {NativeModules, StyleSheet, FlatList, Button, Text, View, TouchableHighlight, RefreshControl, Image, BackHandler} from 'react-native';
import MusicPlayer from "./widget/MusicPlayer";
import {File} from './bean/File';
import IntentLauncher, { IntentConstant } from 'react-native-intent-launcher'

// require the module
var RNFS = require('react-native-fs');
var RNIntent = NativeModules.IntentModule;

export default class DemoFileManager extends Component {

    //设置顶部导航栏的内容
    static navigationOptions = ({navigation, screenProps}) => ({
        //左侧标题
        headerTitle: '文件管理器',
        //设置跳转页面左侧返回箭头后面的文字，默认是上一个页面的标题
        headerBackTitle: null,
        //顶部标题栏的样式
        headerStyle: styles.headerStyle,
        //顶部标题栏文字的样式
        headerTitleStyle: styles.headerTitleStyle,
    });

    constructor(props) {
        super(props);
        this.state = {
            curPath: '',
            fileList : new Array(),
        };
    }

    componentDidMount() {
        this._getSDCardList(RNFS.ExternalStorageDirectoryPath);
        BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
    }

    handleBackPress = () => {
        //处理返回键
        let curPath = this.state.curPath;
        let backPath = curPath.substring(0,curPath.lastIndexOf("/")) ;
        let rootPath = RNFS.ExternalStorageDirectoryPath;
        if (curPath !=  rootPath) {
            this._getSDCardList(backPath);
            return true;
        } else {
            return false;
        }
    }

    _getSDCardList(dirPath) {
        RNFS.readDir(dirPath)
        .then((result) => {
            let curFileList = new Array();
            for (let i=0; i<result.length; i++) {
                //封装数据
                let fileItem = {};
                fileItem.name = result[i].name;
                fileItem.mtime = result[i].mtime;
                fileItem.path = result[i].path;
                fileItem.isDir = result[i].isDirectory() == true;
                fileItem.size = result[i].size;
                curFileList[i] = fileItem;
            }
            this.setState({
                curPath: dirPath,
                fileList:curFileList,
            });
        })
        .catch((error) =>{
            console.log(error.message, error.code);
        })
    }

    render() {
        return (
            <View style={styles.root}>
                <Text style={styles.itemCurPath}>{this.state.curPath}</Text>
                <View style={{height:1, backgroundColor:'#DCDCDC'}} />
                <FlatList
                    ref={ref=>this.flatList=ref}
                    keyExtractor={(item, index) => index.toString()}
                    data={this.state.fileList}
                    extraData={this.state}
                    ItemSeparatorComponent={this._ItemSeparator.bind(this)}
                    renderItem={this._renderItem.bind(this)}
                />
            </View>
         
        );
    }

    async _getDirChildCount(path) {
        if (path == undefined) {
            return 0;
        }
        let fileArray = await RNFS.readDir(path);
        let size = fileArray.length;
        return size;
    }

    _getFileSize(fileByte) {
        let fileSizeByte = fileByte;
        let fileSizeMsg = "";
        if (fileSizeByte < 1024) fileSizeMsg = fileSizeByte + "B";
        else if (1024< fileSizeByte && fileSizeByte < 1048576) fileSizeMsg = (fileSizeByte / 1024) + "KB";
        else if (fileSizeByte == 1048576) fileSizeMsg = "1MB";
        else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824) fileSizeMsg = (fileSizeByte / (1024 * 1024)) + "MB";
        else if (fileSizeByte > 1048576 && fileSizeByte == 1073741824) fileSizeMsg = "1GB";
        else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776) fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)) + "GB";
        else fileSizeMsg = "文件超过1TB";
        return fileSizeMsg;
      }

    _renderItem(item) {
        const {navigate} = this.props.navigation;
        let iconImage = item.item.isDir ? <Image source={require('./image/ic_dir.png')} style={styles.itemImage} />
           :<Image source={require('./image/ic_file.png')} style={styles.itemImage} />;
        let mtime = "";
        if (item.item.mtime != undefined) {
            mtime = item.item.mtime.Format('yyyy-MM-dd hh:mm:ss');
        }

        //处理显示内容
        let detail = '';
        if (item.item.isDir) {
            detail = "";
        } else {
            detail = this._getFileSize(item.item.size) + " | ";
        }

        if (mtime != "") {
            detail = detail + mtime;
        }

        return (
            //渲染item
            <TouchableHighlight underlayColor='#CFCFCF' onPress={() => {
                //跳转详情页面
                console.log("dir:"+item.item.isDir+"  path:"+item.item.path);
                if (item.item.isDir) {
                    this._getSDCardList(item.item.path);
                } else {
                    RNIntent.skipAction(item.item.path);
                }

            }}>
                <View style={styles.itemView}>
                    {iconImage}
                    <View>
                        <Text style={styles.itemTextName}>{item.item.name}</Text>
                        <Text style={styles.itemTextTime}> {detail} </Text>
                    </View>
                </View>
            </TouchableHighlight>
        );
    }

    _ItemSeparator() {
        return <View style={{backgroundColor: '#DCDCDC', height: 1, marginLeft: 10, marginRight: 10}}/>
    }
}

const styles = StyleSheet.create({
    root:{
        flexDirection:"column"
    },
    headerStyle: {
        backgroundColor: '#4398ff',
    },
    headerTitleStyle: {
        //标题的文字颜色
        color: 'white',
        //设置标题的大小
        fontSize: 18,
        //居中显示
        alignSelf: 'center',
    },
    itemView:{
        alignItems: "center",
        flexDirection: 'row',
        height: 64,
        
    },
    itemImage:{
        width: 38,
        height: 38,
        marginLeft: 10,
        marginRight: 10,
    },
    itemTextView:{
        flexDirection:"column"
    },
    itemTextName: {
        fontSize: 15,
    },
    itemTextTime: {
        fontSize: 12,
        marginTop: 3,
    },
    itemCurPath: {
        fontSize: 12,
        marginTop: 3,
        marginBottom: 3,
    },
});